﻿using CCSSolderUI.Common.Domain;
using CCSSolderUI.Common.Event;
using CCSSolderUI.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class MScannerDialogViewModel : BindableBase, IDialogAware
    {
        #region 变量
        SystemParam systemParam;
        Param param;
        IEventAggregator _eventAggregator;
        private readonly IDialogService _dialogService;
        string partName;
        #endregion
        #region 导航
        public string Title => "扫码枪";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            partName = parameters.GetValue<string>("PartNumber");
            LoadParam();
            Update(partName);
        }
        #endregion
        #region 属性绑定
        private string fixedBarcode;
        public string FixedBarcode
        {
            get { return fixedBarcode; }
            set { SetProperty(ref fixedBarcode, value); }
        }
        private string mannulBarcode;
        public string MannulBarcode
        {
            get { return mannulBarcode; }
            set { SetProperty(ref mannulBarcode, value); }
        }
        private string fixedScannerIP;
        public string FixedScannerIP
        {
            get { return fixedScannerIP; }
            set { SetProperty(ref fixedScannerIP, value); }
        }
        private int fixedScannerPort;
        public int FixedScannerPort
        {
            get { return fixedScannerPort; }
            set { SetProperty(ref fixedScannerPort, value); }
        }
        private string mannulScannerCOM;
        public string MannulScannerCOM
        {
            get { return mannulScannerCOM; }
            set { SetProperty(ref mannulScannerCOM, value); }
        }
        private int scannerState;
        public int ScannerState
        {
            get { return scannerState; }
            set { SetProperty(ref scannerState, value); }
        }
        private bool isFixedScannerBusy;
        public bool IsFixedScannerBusy
        {
            get { return isFixedScannerBusy; }
            set { SetProperty(ref isFixedScannerBusy, value); }
        }
        private BarcodeSyntaxDto barcodeSyntaxListSelectedItem;
        public BarcodeSyntaxDto BarcodeSyntaxListSelectedItem
        {
            get { return barcodeSyntaxListSelectedItem; }
            set { SetProperty(ref barcodeSyntaxListSelectedItem, value); }
        }
        private ObservableCollection<BarcodeSyntaxDto> barcodeSyntaxList = new ObservableCollection<BarcodeSyntaxDto>();
        public ObservableCollection<BarcodeSyntaxDto> BarcodeSyntaxList
        {
            get { return barcodeSyntaxList; }
            set { SetProperty(ref barcodeSyntaxList, value); }
        }
        private bool isBarcodeSyntax;
        public bool IsBarcodeSyntax
        {
            get { return isBarcodeSyntax; }
            set { SetProperty(ref isBarcodeSyntax, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> scanTestCommand;
        public DelegateCommand<object> ScanTestCommand =>
            scanTestCommand ?? (scanTestCommand = new DelegateCommand<object>(ExecuteScanTestCommand));
        private DelegateCommand<object> selectScannerCommand;
        public DelegateCommand<object> SelectScannerCommand =>
            selectScannerCommand ?? (selectScannerCommand = new DelegateCommand<object>(ExecuteSelectScannerCommand));
        private DelegateCommand saveButtonCommand;
        public DelegateCommand SaveButtonCommand =>
            saveButtonCommand ?? (saveButtonCommand = new DelegateCommand(ExecuteSaveButtonCommand));
        private DelegateCommand addBarcodeSyntaxCommand;
        public DelegateCommand AddBarcodeSyntaxCommand =>
            addBarcodeSyntaxCommand ?? (addBarcodeSyntaxCommand = new DelegateCommand(ExecuteAddBarcodeSyntaxCommand));
        private DelegateCommand<object> deleteBarcodeSyntaxCommand;
        public DelegateCommand<object> DeleteBarcodeSyntaxCommand =>
            deleteBarcodeSyntaxCommand ?? (deleteBarcodeSyntaxCommand = new DelegateCommand<object>(ExecuteDeleteBarcodeSyntaxCommand));

        void ExecuteDeleteBarcodeSyntaxCommand(object obj)
        {
            if (obj != null)
            {
                var bs = (BarcodeSyntaxDto)obj;
                if (MessageBox.Show($"你确定删除规则{bs.Head}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    using (var sdb = new SysDBContext())
                    {
                        var dbs = sdb.BarcodeSyntaxs.FirstOrDefault(b => b.Id == bs.Id);
                        if (dbs != null)
                        {
                            sdb.Remove(dbs);
                            sdb.SaveChanges();
                        }
                        param.BarcodeSyntaxId = -1;
                    }
                    Update(partName);
                }
            }
            else
            {
                MessageBox.Show($"未选择任何条码", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteAddBarcodeSyntaxCommand()
        {
            _dialogService.ShowDialog("AddNewBarcodeSyntaxDialog", arg =>
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    string NewName = arg.Parameters.GetValue<string>("NewName");
                    if (NewName != "")
                    {
                        using (var sdb = new SysDBContext())
                        {
                            var bs = sdb.BarcodeSyntaxs.FirstOrDefault(b => b.PartName == partName && b.Head == NewName);
                            if (bs != null)
                            {
                                MessageBox.Show($"新规则{NewName}名称重复", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            else
                            {
                                sdb.BarcodeSyntaxs.Add(new BarcodeSyntax() { 
                                    PartName = partName,
                                    Head = NewName
                                });
                                sdb.SaveChanges();
                                var bs1 = sdb.BarcodeSyntaxs.FirstOrDefault(b => b.PartName == partName && b.Head == NewName);
                                if (bs1 != null)
                                {
                                    BarcodeSyntaxList.Add(new BarcodeSyntaxDto()
                                    {
                                        Id = bs1.Id,
                                        Head = bs1.Head
                                    });
                                }
                            }
                        }
                    }
                }
            });
        }
        void ExecuteSaveButtonCommand()
        {
            try
            {
                systemParam.FixedScannerIP = FixedScannerIP;
                systemParam.FixedScannerPort = FixedScannerPort;
                systemParam.MannulScannerCOM = MannulScannerCOM;
                systemParam.ScannerState = ScannerState;
                string jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"), jsonString);

                if (BarcodeSyntaxListSelectedItem != null)
                {
                    param.BarcodeSyntaxId = BarcodeSyntaxListSelectedItem.Id;
                }
                param.IsBarcodeSyntax = IsBarcodeSyntax;
                jsonString = JsonConvert.SerializeObject(param, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partName, "Param.json"), jsonString);

                MessageBox.Show("保存完成", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MScannerDialog", Type = "Update", Content = null });
            }
            catch (Exception ex)
            {
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MScannerDialog", Type = "Print", Content = ex.Message });
            }
        }
        void ExecuteSelectScannerCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "固定":
                    ScannerState = 0;
                    break;
                case "手持":
                    ScannerState = 1;
                    break;
                default:
                    break;
            }
        }
        async void ExecuteScanTestCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "Fixed":
                    {
                        FixedBarcode = "";
                        IsFixedScannerBusy = true;
                        FixedBarcode = await Task.Run(() => { return SHIJIEScanner.Connect(FixedScannerIP, FixedScannerPort, "Start", true); });//55065001141B0421035801147
                        if (FixedBarcode == "Error")
                        {
                            SHIJIEScanner.Connect(FixedScannerIP, FixedScannerPort, "Stop",false);
                        }
                        IsFixedScannerBusy = false;
                    }
                    break;
                default:
                    break;
            }
        }
        #endregion
        #region 构造函数
        public MScannerDialogViewModel(IEventAggregator ea, IDialogService ds)
        {
            FixedBarcode = "";
            MannulBarcode = "";
            IsFixedScannerBusy = false;
            _dialogService = ds;
            _eventAggregator = ea;
            _eventAggregator.GetEvent<MessagePrintEvent>().Subscribe(MessageReceived);
        }


        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"));
                systemParam = JsonConvert.DeserializeObject<SystemParam>(jsonString);
                FixedScannerIP = systemParam.FixedScannerIP;
                FixedScannerPort = systemParam.FixedScannerPort;
                MannulScannerCOM = systemParam.MannulScannerCOM;
                ScannerState = systemParam.ScannerState;
                jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, systemParam.ProductList[systemParam.Index], "Param.json"));
                param = JsonConvert.DeserializeObject<Param>(jsonString);
                IsBarcodeSyntax = param.IsBarcodeSyntax;
            }
            catch (Exception ex)
            {
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MScannerDialog", Type = "Print", Content = ex.Message });
            }
        }
        private void MessageReceived(Common.Event.Message obj)
        {
            switch (obj.Type)
            {
                case "Barcode":
                    MannulBarcode = obj.Content;
                    break;
                case "Select":
                    partName = obj.Content;
                    LoadParam();
                    Update(partName);
                    break;
                case "Delete":
                    if (obj.Sender == "PartNumberDialog")
                    {
                        try
                        {
                            string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"));
                            systemParam = JsonConvert.DeserializeObject<SystemParam>(jsonString);
                        }
                        catch { }
                    }
                    break;
                default:
                    break;
            }
        }
        private void Update(string partname)
        {
            BarcodeSyntaxList.Clear();
            using (var sdb = new SysDBContext())
            {
                var mlist = sdb.BarcodeSyntaxs.Where(b => b.PartName == partname).ToList();
                foreach (var item in mlist)
                {
                    BarcodeSyntaxList.Add(new BarcodeSyntaxDto()
                    {
                        Id = item.Id,
                        Head = item.Head
                    });
                }
            }
            BarcodeSyntaxListSelectedItem = BarcodeSyntaxList.FirstOrDefault(b => b.Id == param.BarcodeSyntaxId);
        }
        #endregion
    }
    public class BarcodeSyntaxDto
    {
        public int Id { get; set; }
        public string Head { get; set; }
    }
}
